import { systemDateTime } from '@kit.BasicServicesKit'
import { hilog } from '@kit.PerformanceAnalysisKit'

/**
 * 防止点击事件
 * @param period 间隔时间
 * @returns
 */
function Debounce(period: number = 750): MethodDecorator {
  return function (
      target: object,
      propertyKey: string,
      descriptor: PropertyDescriptor
  ): PropertyDescriptor {
    const originalMethod = descriptor.value
    let timeId: number = 0
    descriptor.value = function (...args: object[]): void {
      if (timeId !== 0) {
        clearTimeout(timeId)
      }
      timeId = setTimeout(() => {
        originalMethod.apply(this, args)
        timeId = 0
      },
        period
      )
    }
    return descriptor
  }
}

/**
 * 监听某个方法的耗时
 */
function MonitorCostTime(): MethodDecorator {
  return function (target: object,
    propertyKey: string,
    descriptor: PropertyDescriptor) {
    const originMethod = descriptor.value

    descriptor.value = function (...args: object[]) {
      let startTime = systemDateTime.getTime()
      const result = originMethod.apply(this, args); // 调用原始方法
      const endTime = systemDateTime.getTime(); // 获取方法执行后的时间
      hilog.error(hilog.LogLevel.ERROR, "monitorCostTime", `方法消耗的时间为：${endTime - startTime}s`)
      return result;
    }
    return descriptor
  }
}


export {
  Debounce, MonitorCostTime
}